package com.xiaxueqi.web.reg;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.niagara.components.email.AsyncMailSender;
import com.niagara.context.SecurityContext;
import com.niagara.security.auth.exception.AuthException;
import com.niagara.service.base.BaseService;
import com.niagara.web.struts2.CRUDActionSupport;
import com.niagara.web.struts2.Struts2Utils;
import com.octo.captcha.service.CaptchaService;
import com.octo.captcha.service.CaptchaServiceException;
import com.xiaxueqi.entity.security.AppUser;
import com.xiaxueqi.entity.security.AppUserDetail;
import com.xiaxueqi.entity.security.AppUserRole;
import com.xiaxueqi.service.RegService;
import com.xiaxueqi.service.ServiceException;

import freemarker.template.Configuration;

/**
 * 用户注册Action
 * 
 * @author zcq1987
 * 
 */
@Results( {
		@Result(name = "login", location = "/login.action", type = "redirect"),
		@Result(name = "error", location = "/reg/register.action", type = "redirect") })
public class RegisterAction extends CRUDActionSupport<AppUser> {
	/**
	 * 
	 */
	private static final long serialVersionUID = 3912214512955183899L;

	private String loginId;
	private AsyncMailSender asyncMailSender;
	private Configuration freemarkerConfiguration;
	private CaptchaService captchaService;
	private String captchaKey = "checkCode";

	@Autowired
	private BaseService baseService;

	@Autowired
	private RegService regService;

	private AppUser appUser;

	public void setLoginId(String loginId) {
		this.loginId = loginId;
	}

	public void setAsyncMailSender(AsyncMailSender asyncMailSender) {
		this.asyncMailSender = asyncMailSender;
	}

	public void setFreemarkerConfiguration(Configuration freemarkerConfiguration) {
		this.freemarkerConfiguration = freemarkerConfiguration;
	}

	public CaptchaService getCaptchaService() {
		return captchaService;
	}

	public void setCaptchaService(CaptchaService captchaService) {
		this.captchaService = captchaService;
	}

	public void setBaseService(BaseService baseService) {
		this.baseService = baseService;
	}

	public void setRegService(RegService regService) {
		this.regService = regService;
	}

	@Override
	public String execute() {
		return SUCCESS;
	}

	public AppUser getModel() {
		// TODO Auto-generated method stub
		return appUser;
	}

	@Override
	public String delete() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String list() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void prepareModel() throws Exception {
		// TODO Auto-generated method stub
		appUser = new AppUser();
	}

	/**
	 * 保存用户注册信息
	 */
	@Override
	public String save() throws Exception {
		// TODO Auto-generated method stub

		// 判断验证码是否正确
		HttpServletRequest request = SecurityContext.getRequest();
		String captcha = request.getParameter(this.captchaKey);
		String captchaID = request.getSession().getId();
		boolean success = false;
		try {
			success = captchaService.validateResponseForID(captchaID, captcha);
		} catch (CaptchaServiceException e) {
			logger.error(e.getMessage(), e);
			throw new AuthException(e);
		}
		if (!success)
			return ERROR;

		if (appUser != null && !appUser.getLoginId().trim().equals("")
				&& !appUser.getPassword().trim().equals("")) {
			
//			appUser.setPassword(DigestUtils.md5Hex(appUser.getLoginId()
//					+ appUser.getPassword()));

			// 判断用户名是否存在
			if (this.baseService.get(AppUser.class, appUser,
					"select_by_condition") != null)
				return ERROR;

			// 随机生成激活码
			AppUserDetail aud = new AppUserDetail();
			Double d = Math.random();
			String activeNum = d.toString().substring(2, 10);
			aud.setActiveNum(activeNum);
			String showMore = Struts2Utils.getParameter("show_more");
			if (showMore != null && showMore.equals("1")) {
				aud.setAddress(Struts2Utils.getParameter("address"));
				aud.setMsn(Struts2Utils.getParameter("msn"));
				aud.setName(Struts2Utils.getParameter("name"));
				aud.setNickName(Struts2Utils.getParameter("nickName"));
				aud.setOrgName(Struts2Utils.getParameter("university"));
				aud.setQq(Struts2Utils.getParameter("qq"));
				aud.setSex(Struts2Utils.getParameter("sex"));
				aud.setTel(Struts2Utils.getParameter("tel"));
			}

			// 用户角色
			AppUserRole aur = new AppUserRole();

			// 执行插入
			try {
				this.regService.doRegister(appUser, aud, aur);
			} catch (ServiceException se) {
				se.printStackTrace();
				return ERROR;
			}

			// 发送激活邮件
			/*
			String url = Struts2Utils.getRequest().getRequestURL().toString()
					.replace("save.action", "active.action");
			String content = url + "?id=" + appUser.getId() + "&activeNum="
					+ activeNum;
			System.out.println(content);
			this.asyncMailSender.sendMail("xiaxueqi.com@gmail.com",
					new String[] { loginId }, null, null, "注册确认邮件", content,
					null, null, null, false);
			*/
		} else
			return ERROR;
		return LOGIN;
	}

	/**
	 * 验证用户名是否有效
	 * 
	 * @return
	 */
	public String check() {
		AppUser au = new AppUser();
		au.setLoginId(loginId);
		AppUser rtApp = this.baseService.get(AppUser.class, au,
				"select_by_condition");
		if (rtApp != null) {
			Struts2Utils.renderText("N");
		} else {
			Struts2Utils.renderText("Y");
		}
		return NONE;
	}

	/**
	 * 激活用户
	 * 
	 * @return
	 */
	public String active() {
		try {
			String activeNum = Struts2Utils.getParameter("activeNum");
			if (activeNum == null || activeNum.equals(""))
				return ERROR;
			String id = Struts2Utils.getParameter("id");
			if (id == null || id.equals(""))
				return ERROR;
			AppUserDetail aud = new AppUserDetail();
			aud.setId(Integer.valueOf(id));
			AppUser au = new AppUser();
			AppUserRole aur = new AppUserRole();
			if (baseService
					.get(AppUserDetail.class, aud, "select_by_condition") != null) {
				au.setId(aud.getId());
				au.setDeleted("N");
				aur.setId(aud.getId());
				aur.setDeleted("N");
				regService.doActive(au, aud, aur);
			} else
				return ERROR;
		} catch (RuntimeException e) {
			return ERROR;
		}
		return LOGIN;
	}
}
